package com.stox.client.ui.javafx.chartingy.widget.menu;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;

import com.stox.client.ui.javafx.chartingy.model.enumeration.Overlay;
import com.stox.client.ui.javafx.chartingy.view.ChartingView;
import com.stox.client.ui.javafx.widget.ContextMenuConfigurerRegistry;
import com.stox.shared.i18n.MessageSource;
import com.stox.shared.model.Scrip;
import com.stox.shared.model.intf.HasScrip;

public class ChartingContextMenu extends ContextMenu implements HasScrip {

	private final ChartingView chartingView;

	public ChartingContextMenu(final ChartingView chartingView) {
		this.chartingView = chartingView;
		setAutoHide(true);
		getItems().addAll(createMaintainRatioMenuItem(), createVolumeMenu());
		ContextMenuConfigurerRegistry.getInstance().attachContextMenu(this);
	}

	private MenuItem createMaintainRatioMenuItem() {
		final CheckMenuItem menuItem = new CheckMenuItem(MessageSource.get("Maintain.Ratio"));
		menuItem.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(final ActionEvent event) {
				chartingView.setMaintainRatio(menuItem.isSelected());
			}
		});
		return menuItem;
	}

	private Menu createVolumeMenu() {
		final Menu menu = new Menu(MessageSource.get("Volume"));
		final MenuItem hideMenuItem = new MenuItem(MessageSource.get("Hide"));
		menu.getItems().add(hideMenuItem);
		hideMenuItem.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(final ActionEvent event) {
				chartingView.getVolumePlot().setOverlay(Overlay.VOLUME);
			}
		});
		final MenuItem showOnPriceChartMenuItem = new MenuItem(MessageSource.get("Show.On.Price.Chart"));
		menu.getItems().add(showOnPriceChartMenuItem);
		showOnPriceChartMenuItem.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(final ActionEvent event) {
				chartingView.getVolumePlot().setOverlay(Overlay.PRICE);
			}
		});
		final MenuItem showSeparetelyMenuItem = new MenuItem(MessageSource.get("Show.Separately"));
		menu.getItems().add(showSeparetelyMenuItem);
		showSeparetelyMenuItem.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(final ActionEvent event) {
				chartingView.getVolumePlot().setOverlay(null);
			}
		});
		return menu;
	}

	@Override
	public Scrip getScrip() {
		return null == chartingView ? null : (null == chartingView.getPrimaryChart().getPrimaryPlot() ? null : chartingView.getPrimaryChart().getPrimaryPlot().getExtraValue());
	}

	@Override
	public void setScrip(final Scrip scrip) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Long getScripId() {
		final Scrip scrip = getScrip();
		return null == scrip ? null : scrip.getId();
	}

}
